

const crypto = require("crypto");   // Node 自带API 

// 加密函数  aes  data 需要加密的字段 
function aesEncrypt(data, key) {
    const cipher = crypto.createCipher('aes192', key);
    var crypted = cipher.update(data, 'utf8', 'hex');
    crypted += cipher.final('hex');
    return crypted;  // 密文  
}

// 解密 
function aesDecrypt(encrypted, key) {
    const decipher = crypto.createDecipher('aes192', key);
    var decrypted = decipher.update(encrypted, 'hex', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;  // 明文 
}

const keys = "WUHAN2002DAYDAYUP";   //   abc123 ==> abc123WUHAN2002DAYDAYUP 

exports.aesEncrypt = aesEncrypt;   // 加密
exports.aesDecrypt = aesDecrypt;   // 解密
exports.keys = keys;        // 密钥 



exports.dateFormat = function(value){
    var date = new Date(value);
    var hour = date.getHours();
    var min = date.getMinutes();
    var sec = date.getSeconds();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day =  date.getDate();

    return `${year}-${month}-${day} ${hour}:${min}`;
}



// 中间件  middleware 
exports.checkToken = function(req,res,next){
    var server_token = req.session.token;
    var client_token = req.headers.token;
    console.log(req.path);
    console.log('server---'+server_token)
    
    if(req.path!=='/vue/signin'&&req.path!=="/vue/signup"){
        // token 判断
        console.log('client---'+client_token)
        if(client_token){
            if(server_token){
                if(client_token==server_token){
                    next(); // token 有效
                }else{
                    res.json({
                        msg:"token 无效",
                        code:"3000",
                        type:0
                    })
                }
            }else{
                res.json({
                    msg:"token 失效",
                    code:"3000",
                    type:0
                })
            }
        }else{
            res.json({
                msg:"token 不存在",
                code:"3000",
                type:0
            })
        }
    }else{
        next();
    }

}